// src/router/index.ts
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import HomeView from '../views/HomeView.vue'


const modules = import.meta.glob("../views/**/**.vue")
// 原始路由配置
const routes: RouteRecordRaw[] = [
  {
      path: "/:pathMatch(.*)*", 
      component: () => import("@/views/common/NotfoundPage.vue"), 
    },
  {
    path: '/',
    name: 'home',
    component: HomeView,
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue'),
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/common/LoginPage.vue'),
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('../views/common/RegisterPage.vue'),
  },
  {
    path: '/me',
    name: 'me',
    component: () => import('../views/common/AboutMePage.vue'),
  },
  {
    path: '/product/:id',
    name: 'productinfo',
    component: () => import('../views/common/GoodInfo.vue'),
  },
  {
    path: '/product/search/:keyword',
    name: 'prodsearch',
    component: () => import('../views/common/SearchPage.vue'),
  },
  {
    path: '/test',
    component: () => import('@/views/ztest/ZTestFatherView.vue'),
    children: [
      {
        path: 'son1',
        name: 'Son1',
        component: () => import('@/views/ztest/ZTestChildrenView1.vue'),
        children:[]
      },
      {
        path: 'son2',
        name: 'Son2',
        component: () => import('@/views/ztest/ZTestChildrenView2.vue'),
      },
      {
        path: 'piniat',
        name: 'piniat',
        component: () => import('@/views/ztest/getPiniaView.vue'),
      },
    ],
  },
  {
    path: '/store',
    name: 'store',
    component: () => import('@/views/common/StoreView.vue'),
  },
  {
    path:'/order/detail/:orderNum',
    name: 'orderdetail',
    component: () => import('@/views/common/OrderDetail.vue'),
  },
  {
    path: '/management',
    name: 'management',
    component: () => import('../views/management/DashboardLayout.vue'),
    children: [
      {
        path:'',
        component: () => import('../views/management/DashboardView.vue'),
      },
    {
      path: 'dashboard',
      name: 'dashboard',
      component: () => import('../views/management/DashboardView.vue'),
    }
  ] 
  },
  {
    path: '/my-orders',
    name: 'my-orders',
    component: () => import('../views/common/MyOrders.vue'),
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  // history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  // 添加路由导航守卫逻辑
  import('@/stores/user').then(({ useUserStore })=>{
    const userStore = useUserStore()
    if (to.path.startsWith("/management")) {
      if (!userStore.getMenus) {
          next('/login')
          return
        }
        if(!userStore.getRouterCreated) addManagementRoutes(userStore.getMenus)
        // console.log(router.getRoutes())
        next({ ...to, replace: true })
        return
     }
     
  })
  
  next()
})

// 动态添加管理路由的函数
export function addManagementRoutes(menuData: any[]) {
  const managementRoute = routes.find(route => route.path === '/management')
  
  if (managementRoute && managementRoute.children) {
    // 递归处理菜单数据并转换为路由配置
    const generateRoutes = (menus: any[]): RouteRecordRaw[] => {
      return menus.map(menu => {
        const route: RouteRecordRaw = {
          path: menu.path,
          name: menu.name,
          ...(menu.children && menu.children.length > 0 
            ? {} 
            : { component: modules[menu.component] }
          ),
          children: menu.children ? generateRoutes(menu.children) : []
        }
        return route
      })
    }

    // 将菜单数据转换为路由并添加到management路由下
    const newRoutes = generateRoutes(menuData)
    managementRoute.children.push(...newRoutes)
    
    // 使用 router.addRoute 动态添加路由
    newRoutes.forEach(route => {
      router.addRoute('management', route)
    })
  }
}

export default router